package org.jeecg.modules.oms.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.oms.entity.OmsInquiry;
import org.jeecg.modules.oms.entity.OmsInquiryItem;
import org.jeecg.modules.oms.service.IOmsInquiryService;
import org.jeecg.modules.oms.service.IOmsInquiryItemService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;

/**
 * @Description: 询单表
 * @Author: jeecg-boot
 * @Date: 2025-09-29
 * @Version: V1.0
 */
@Api(tags="询单表")
@RestController
@RequestMapping("/oms/inquiry")
@Slf4j
public class OmsInquiryController extends JeecgController<OmsInquiry, IOmsInquiryService> {
	@Autowired
	private IOmsInquiryService omsInquiryService;
	@Autowired
	private IOmsInquiryItemService omsInquiryItemService;
	
	/**
	 * 分页列表查询
	 *
	 * @param omsInquiry
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "询单表-分页列表查询")
	@ApiOperation(value="询单表-分页列表查询", notes="询单表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(OmsInquiry omsInquiry,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<OmsInquiry> queryWrapper = new QueryWrapper<>();
		
		// 客户名称模糊查询
		if (omsInquiry.getCustomerName() != null && !omsInquiry.getCustomerName().trim().isEmpty()) {
			queryWrapper.like("customer_name", omsInquiry.getCustomerName().trim());
		}
		
		// 客户电话模糊查询
		if (omsInquiry.getCustomerPhone() != null && !omsInquiry.getCustomerPhone().trim().isEmpty()) {
			queryWrapper.like("customer_phone", omsInquiry.getCustomerPhone().trim());
		}
		
		// 收货地址模糊查询
		if (omsInquiry.getDeliveryAddress() != null && !omsInquiry.getDeliveryAddress().trim().isEmpty()) {
			queryWrapper.like("delivery_address", omsInquiry.getDeliveryAddress().trim());
		}
		
		// 状态精确查询
		if (omsInquiry.getStatus() != null) {
			queryWrapper.eq("status", omsInquiry.getStatus());
		}
		
		// 物流类型精确查询
		if (omsInquiry.getLogisticsType() != null) {
			queryWrapper.eq("logistics_type", omsInquiry.getLogisticsType());
		}
		
		// 门类型精确查询
		if (omsInquiry.getType() != null) {
			queryWrapper.eq("type", omsInquiry.getType());
		}
		
		// 询单日期精确查询
		String inquiryDate = req.getParameter("inquiryDate");
		if (inquiryDate != null && !inquiryDate.trim().isEmpty()) {
			queryWrapper.eq("DATE(inquiry_date)", inquiryDate);
		}
		
		// 添加排序
		queryWrapper.orderByDesc("create_time");
		
		Page<OmsInquiry> page = new Page<OmsInquiry>(pageNo, pageSize);
		IPage<OmsInquiry> pageList = omsInquiryService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param requestBody
	 * @return
	 */
	@AutoLog(value = "询单表-添加")
	@ApiOperation(value="询单表-添加", notes="询单表-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody Map<String, Object> requestBody) {
		try {
			OmsInquiry inquiry = new OmsInquiry();
			inquiry.setCustomerName((String) requestBody.get("customerName"));
			inquiry.setCustomerPhone((String) requestBody.get("customerPhone"));
			inquiry.setDeliveryAddress((String) requestBody.get("deliveryAddress"));
			
			// 安全类型转换
			Object logisticsTypeObj = requestBody.get("logisticsType");
			if (logisticsTypeObj != null) {
				if (logisticsTypeObj instanceof String) {
					inquiry.setLogisticsType(Integer.parseInt((String) logisticsTypeObj));
				} else if (logisticsTypeObj instanceof Integer) {
					inquiry.setLogisticsType((Integer) logisticsTypeObj);
				}
			}
			
			Object statusObj = requestBody.get("status");
			if (statusObj != null) {
				if (statusObj instanceof String) {
					inquiry.setStatus(Integer.parseInt((String) statusObj));
				} else if (statusObj instanceof Integer) {
					inquiry.setStatus((Integer) statusObj);
				}
			}
			
			inquiry.setRemark((String) requestBody.get("remark"));

			Object typeObj = requestBody.get("type");
			if (typeObj != null) {
				if (typeObj instanceof String) {
					inquiry.setType(Integer.parseInt((String) typeObj));
				} else if (typeObj instanceof Integer) {
					inquiry.setType((Integer) typeObj);
				}
			}

			inquiry.setRemark((String) requestBody.get("remark"));

			
			// 处理询单明细
			Object itemsObj = requestBody.get("items");
			if (itemsObj != null) {
				List<Map<String, Object>> itemMaps = (List<Map<String, Object>>) itemsObj;
				List<OmsInquiryItem> items = itemMaps.stream().map(itemMap -> {
					OmsInquiryItem item = new OmsInquiryItem();
					item.setRuleId((String) itemMap.get("ruleId"));
					item.setRuleName((String) itemMap.get("ruleName"));
					item.setRuleValue((String) itemMap.get("ruleValue"));
					
					Object sortNoObj = itemMap.get("sortNo");
					if (sortNoObj != null) {
						if (sortNoObj instanceof String) {
							item.setSortNo(Integer.parseInt((String) sortNoObj));
						} else if (sortNoObj instanceof Integer) {
							item.setSortNo((Integer) sortNoObj);
						}
					}
					
					return item;
				}).collect(Collectors.toList());
				inquiry.setItems(items);
			}
			
			omsInquiryService.saveInquiryWithItems(inquiry);
			return Result.OK("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("操作失败：" + e.getMessage());
		}
	}
	
	/**
	 * 通过id查询询单详情（包含排序的明细）
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询单表-通过id查询详情")
	@ApiOperation(value="询单表-通过id查询详情", notes="询单表-通过id查询详情")
	@GetMapping(value = "/queryById")
	public Result<OmsInquiry> queryById(@RequestParam(name="id",required=true) String id) {
		try {
			OmsInquiry inquiry = omsInquiryService.getById(id);
			if (inquiry != null) {
				// 查询询单明细，按照关联的规则表的sort_no排序
				QueryWrapper<OmsInquiryItem> itemWrapper = new QueryWrapper<>();
				itemWrapper.eq("inquiry_id", id);
				itemWrapper.orderByAsc("sort_no");
				List<OmsInquiryItem> items = omsInquiryItemService.list(itemWrapper);
				inquiry.setItems(items);
			}
			return Result.OK(inquiry);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("查询失败：" + e.getMessage());
		}
	}
	
	/**
	 *  编辑
	 *
	 * @param requestBody
	 * @return
	 */
	@AutoLog(value = "询单表-编辑")
	@ApiOperation(value="询单表-编辑", notes="询单表-编辑")
	@PutMapping(value = "/edit")
	public Result<String> edit(@RequestBody Map<String, Object> requestBody) {
		try {
			OmsInquiry inquiry = new OmsInquiry();
			inquiry.setId((String) requestBody.get("id"));
			inquiry.setCustomerName((String) requestBody.get("customerName"));
			inquiry.setCustomerPhone((String) requestBody.get("customerPhone"));
			inquiry.setDeliveryAddress((String) requestBody.get("deliveryAddress"));
			inquiry.setStatus(1);
			
			// 安全类型转换
			Object logisticsTypeObj = requestBody.get("logisticsType");
			if (logisticsTypeObj != null) {
				if (logisticsTypeObj instanceof String) {
					inquiry.setLogisticsType(Integer.parseInt((String) logisticsTypeObj));
				} else if (logisticsTypeObj instanceof Integer) {
					inquiry.setLogisticsType((Integer) logisticsTypeObj);
				}
			}
			
			Object statusObj = requestBody.get("status");
			if (statusObj != null) {
				if (statusObj instanceof String) {
					inquiry.setStatus(Integer.parseInt((String) statusObj));
				} else if (statusObj instanceof Integer) {
					inquiry.setStatus((Integer) statusObj);
				}
			}

			Object typeObj = requestBody.get("type");
			if (typeObj != null) {
				if (typeObj instanceof String) {
					inquiry.setType(Integer.parseInt((String) typeObj));
				} else if (typeObj instanceof Integer) {
					inquiry.setType((Integer) typeObj);
				}
			}

			Object totalPriceObj = requestBody.get("totalPrice");
			if (totalPriceObj != null) {
				if (totalPriceObj instanceof String) {
					inquiry.setTotalPrice(Double.parseDouble((String) totalPriceObj));
				} else if (totalPriceObj instanceof Integer) {
					inquiry.setTotalPrice((Double) totalPriceObj);
				}
			}
			
			inquiry.setRemark((String) requestBody.get("remark"));
			
			// 处理询单明细
			Object itemsObj = requestBody.get("items");
			if (itemsObj != null) {
				List<Map<String, Object>> itemMaps = (List<Map<String, Object>>) itemsObj;
				List<OmsInquiryItem> items = itemMaps.stream().map(itemMap -> {
					OmsInquiryItem item = new OmsInquiryItem();
					item.setRuleId((String) itemMap.get("ruleId"));
					item.setRuleName((String) itemMap.get("ruleName"));
					item.setRuleValue((String) itemMap.get("ruleValue"));
					
					Object sortNoObj = itemMap.get("sortNo");
					if (sortNoObj != null) {
						if (sortNoObj instanceof String) {
							item.setSortNo(Integer.parseInt((String) sortNoObj));
						} else if (sortNoObj instanceof Integer) {
							item.setSortNo((Integer) sortNoObj);
						}
					}
					
					return item;
				}).collect(Collectors.toList());
				inquiry.setItems(items);
			}
			
			omsInquiryService.updateInquiryWithItems(inquiry);
			return Result.OK("编辑成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("操作失败：" + e.getMessage());
		}
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询单表-通过id删除")
	@ApiOperation(value="询单表-通过id删除", notes="询单表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		omsInquiryService.deleteInquiryWithItems(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "询单表-批量删除")
	@ApiOperation(value="询单表-批量删除", notes="询单表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		String[] idArray = ids.split(",");
		for (String id : idArray) {
			omsInquiryService.deleteInquiryWithItems(id);
		}
		return Result.OK("批量删除成功!");
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param omsInquiry
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, OmsInquiry omsInquiry) {
		return super.exportXls(request, omsInquiry, OmsInquiry.class, "询单表");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, OmsInquiry.class);
	}

	/**
	 * 完结询单
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "询单表-完结询单")
	@ApiOperation(value="询单表-完结询单", notes="询单表-完结询单")
	@PutMapping(value = "/complete/{id}")
	public Result<String> complete(@PathVariable(name="id",required=true) String id) {
		try {
			OmsInquiry inquiry = omsInquiryService.getById(id);
			if (inquiry == null) {
				return Result.error("询单不存在!");
			}
			
			if (inquiry.getStatus() == 2) {
				return Result.error("询单已经是完成状态!");
			}
			
			// 更新状态为已完成(2)
			inquiry.setStatus(2);
			omsInquiryService.updateById(inquiry);
			
			return Result.OK("询单完结成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error("完结询单失败：" + e.getMessage());
		}
	}

}
